package com.base.controller;

import com.base.comm.CommUrls;
import com.base.helper.VosHelper;
import com.base.helper.WebHelper;
import com.base.po.czb_sdk.GasOrder;
import com.base.po.param.NetState;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Users;
import com.base.service.CZB.GasOrderService;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import com.base.utils.Page;
import com.base.utils.Produce;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class GasRefundController {
    @Autowired
    GasOrderService gasOrderService;
    @Autowired
    SubscribersService subscribersService;
    @Autowired
    UsersService usersService;

    @RequestMapping("/content_gasorder")
    public ModelAndView index(HttpServletRequest request, Integer currentPageNo, String status,
                              String mobile, String czborderid, String czbordersn, String gasid, String paystatus, String createTime1, String createTime2) throws Exception {
        Map<String, Object> map = new HashMap<>(); // 返回数据对象
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        if (adminUserId == null) {
            return new ModelAndView("jsp/content_gasorder", map);
        }

        if (currentPageNo == null) {
            currentPageNo = 1;
        }
        if (paystatus == null || paystatus.equals("") || paystatus.equals("6")) {
            paystatus = null;
        }

        Subscribers subscribers;
        String userId = null;

        if (mobile == null || mobile.equals("")) {
            mobile = null;
        } else {
            if (!Produce.isMobile(mobile)) {
                map.put("msg", "请输入正确的手机号");
                return new ModelAndView("jsp/content_gasorder", map);
            }
            subscribers = subscribersService.selectBySubscribers(mobile, adminUserId);
            if (subscribers == null) {
                userId = null;
            } else {
                userId = subscribers.getId();
            }
        }

        if (czborderid == null || czborderid.equals("")) {
            czborderid = null;
        }

        if (czbordersn == null || czbordersn.equals("")) {
            czbordersn = null;
        }

        if (gasid == null || gasid.equals("")) {
            gasid = null;
        }

        if (paystatus == null || paystatus.equals("")) {
            paystatus = null;
        }

        // 设置分页 获取内容
        Page page = new Page(); // 实例化分页
        if (currentPageNo != null) page.setCurrentPageNo(currentPageNo); // 设置当前页

        page.setCurrentPage((currentPageNo - 1) * page.getPageSize());

        Integer gasOrderCount = gasOrderService.countAllGasOrder(userId, czborderid, czbordersn, gasid, paystatus, createTime1, createTime2);

        List<GasOrder> gasOrders = gasOrderService.selectAllGasOrder(userId, czborderid, czbordersn, gasid, paystatus, createTime1, createTime2, page);
        gasOrders.forEach(item -> {
            Subscribers sub = subscribersService.selectByPrimaryKey(item.getUserid());
            if (sub!=null){
                String mobile1 = sub.getMobile();
                item.setMobile(mobile1);
            }

        });

        page.setRecordTotal(gasOrderCount); // 设置总条数
        map.put("mobile", mobile);
        map.put("czborderid", czborderid);
        map.put("czbordersn", czbordersn);
        map.put("gasid", gasid);
        map.put("paystatus", paystatus);
        map.put("gasOrderList", gasOrders); // 提现集合
        map.put("status", status); // 状态
        map.put("pages", page); // 分页
        return new ModelAndView("jsp/content_gasorder", map);
    }

    //真实退款，点击申请会退款
    @RequestMapping("/refundMoneySuccess")
    public @ResponseBody
    Map<String, String> success(HttpServletRequest request, String id, String userId, String orderId, String parentId) {
        Map<String, String> map = new HashMap<>();

        if (id == null || userId == null || parentId == null || orderId == null) {
            map.put("status", "400");
            map.put("msg", "数据不全");
            return map;
        }
        Users users = usersService.selectByPrimaryKey(parentId);
        Subscribers sub = subscribersService.selectByPrimaryKey(userId);

        GasOrder gasOrder = gasOrderService.selectByPrimaryKey(orderId);

        if (gasOrder == null) {
            map.put("status", "500");
            map.put("msg", "订单不存在");
            return map;
        }
        String refundResult="";
        int code;
        synchronized (this) {
            GasOrder gasOrderNow = gasOrderService.selectByPrimaryKey(orderId);
            if (gasOrderNow.getPaystatus().equals(5)) {
                refundResult = WebHelper.PostData(CommUrls.THISSERVER + "aliPayment/gasRefund", "userId=" + gasOrder.getUserid() + "&orderId=" + gasOrder.getId(), null, null);
            }else {
                map.put("status", "500");
                map.put("msg", "订单状态已更新，请刷新重试");
                return map;
            }
        }
        NetState netState = (NetState) JSONObject.toBean(JSONObject.fromObject(refundResult), NetState.class);

        if (netState.getErrorCode() == 2000) {
            code = gasOrderService.updateByPrimaryKeySelective(gasOrder);
            if (code < 1) {
                map.put("status", "201");
                map.put("msg", "订单已成功退钱，但是数据库更新失败，请联系管理员");
            }
            // 扣除话费
            Subscribers user = subscribersService.selectByPrimaryKey(gasOrder.getUserid());
            Users agent = usersService.selectByPrimaryKey(user.getParentid());
            BigDecimal sbdFree = gasOrder.getAmountgun().subtract(gasOrder.getSbdpayamount()).setScale(2, BigDecimal.ROUND_HALF_UP);
            VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix() + user.getMobile()
                    + "\",\"ownerType\":\"2\",\"money\":\"" + sbdFree + "\",\"memo\":\"" + user.getUsername()
                    + "，加油退回" + sbdFree + "元\"}");
            map.put("status", "200");
            map.put("msg", "成功");
        } else {
            map.put("status", "501");
            map.put("msg", "支付宝扣款失败");
        }
        return map;
    }
}
